#include<arpa/inet.h>
#include<stdlib.h>
#include<iostream>
#include<stdio.h>


#define SIZE 4096
#define MAX_CLIENTS 5

using namespace  std;

void close_connection( int client_socket) {
		shutdown(client_socket, SHUT_RDWR);
		close(client_socket);
}

int talk_with_client(int socket) {
	char buffer[SIZE];
	int size = 0;
	while(true) {
		size = recv(socket, buffer, SIZE,0);
		if(size <= 0) {
			if(size < 0)
				perror("Receive: ");
			close_connection(socket);
			return -1;
		} else {	
			cout << "From client: " << buffer << endl;
			size = send(socket,buffer,size,0);
			if(size < 0) {
				perror("Send: ");
				close_connection(socket);
				return -1;
			}
		}
	}
return 0;
}

int main(int argc, char** argv)
{
	cout << "Echo server" << endl;
	    
    int listen_sckt = socket (AF_INET, SOCK_STREAM, 0);
	if(listen_sckt == -1) {	
		perror("Opening socket: ");
		close(listen_sckt);
		return -1;
	}
	
	sockaddr_in *client = new sockaddr_in;
	int errcheck = 0;
	sockaddr_in *server = new sockaddr_in;
	server->sin_family = AF_INET;
	server->sin_addr.s_addr = INADDR_ANY;
	server->sin_port = htons ((errcheck = atoi(argv[1])));
	if(errcheck ==0) {
		close(listen_sckt);
		return 0;
	}
	errcheck = bind(listen_sckt,(sockaddr*)server,sizeof(sockaddr_in));
	
	errcheck = listen(listen_sckt,MAX_CLIENTS);
	if(errcheck == -1)
	{
		perror("Listen: ");
		close(listen_sckt);
		delete server;
		delete client;
		return errcheck;
	}
	
    unsigned int a =  sizeof(sockaddr_in);
    int client_sckt = accept(listen_sckt,(sockaddr*)client, &a);
	talk_with_client(client_sckt);
	
	close(listen_sckt);
	delete server;
	delete client;
	return 0;
}
